<template>
  <page-layout>
    <a-card>
      <a-button size="large" @click="$router.go(-1)">返回</a-button>
      <a-form
        style="margin-top: 36px"
        :form="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-form-item label="名称" :required="true">
          <a-input
            placeholder="请输入任务名称"
            size="large"
            v-decorator="[
              'title',
              {
                rules: [{ required: true, message: '请输入任务名称!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item label="部门" :required="true">
          <a-select
            placeholder="请选择部门"
            size="large"
            v-decorator="[
              'department_id',
              { rules: [{ required: true, message: '请选择部门!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[0]"
              :key="item.department_id"
              :value="item.department_id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="对接人" :required="true">
          <a-select
            placeholder="请选择对接人"
            size="large"
            v-decorator="[
              'docking_id',
              { rules: [{ required: true, message: '请选择对接人!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[1]"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="工程师" :required="true">
          <a-select
            placeholder="请选择工程师"
            size="large"
            v-decorator="[
              'engineer_id',
              { rules: [{ required: true, message: '请选择工程师!' }] }
            ]"
            @change="handleSelectChange"
          >
            <a-select-option
              v-for="item in selectDatas[3]"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <div v-if="!this.$route.query.demand_id">
          <a-form-item label="关联需求" :required="false">
            <a-select
              placeholder="请选择关联需求"
              size="large"
              v-decorator="[
                'requirement_id',
                { rules: [{ required: false, message: '请选择关联需求!' }] }
              ]"
              @change="handleRequirementChange"
            >
              <a-select-option
                v-for="item in selectDatas[2]"
                :key="item.requirement_id"
                :value="item.requirement_id"
              >
                {{ item.title || "未命名需求" }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item  v-if="principal_select"
            label="需求负责人"
            :required="false"
          >
            <a-select
              v-if="!principal"
              placeholder="请选择需求负责人"
              size="large"
              v-decorator="[
                'principal_id',
                { rules: [{ required: false, message: '请选择需求负责人!' }] }
              ]"
              @change="handleSelectChange"
            >
              <a-select-option
                v-for="item in selectDatas[3]"
                :key="item.id"
                :value="item.id"
              >
                {{item.name}}
              </a-select-option>
            </a-select>
            <a-input
             v-if="principal"
              disabled
              size="large"
              v-decorator="[
                'principal',
                {
                  initialValue: principal
                }
              ]"
              >{{principal}}</a-input
            >
          </a-form-item>
        </div>
        <div v-else>
          <a-form-item label="关联需求" :required="false">
            <a-select
              placeholder="请选择关联需求"
              size="large"
              disabled
              v-decorator="[
                'requirement_id',
                { rules: [{ required: false, message: '请选择关联需求!' }] }
              ]"
              @change="handleSelectChange"
            >
              <a-select-option
                v-for="item in selectDatas[2]"
                :key="item.requirement_id"
                :value="item.requirement_id"
              >
                {{ item.title || "未命名需求" }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            label="需求负责人"
            :required="false"
          
          >
            <a-select
              v-if="!editData.principal_id"
              placeholder="请选择需求负责人"
              size="large"
              v-decorator="[
                'principal_id',
                { rules: [{ required: false, message: '请选择需求负责人!' }] }
              ]"
              @change="handlePrincipalChange"
            >
              <a-select-option
                v-for="item in selectDatas[3]"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-input
              v-if="editData.principal_id"
              disabled
              size="large"
              v-decorator="[
                'principal',
                {
                  initialValue: editData.principal
                }
              ]"
              >{{ editData.principal }}</a-input
            >
          </a-form-item>
        </div>
        <a-form-item label="任务详情">
          <EditorBar
            v-decorator="[
              'description',
              ,
              {
                rules: [{ required: true, message: '请输入任务详情!' }]
              }
            ]"
            :isClear="isClear"
          />
        </a-form-item>
        <a-form-item label="计划开始时间" :required="true">
          <a-date-picker
            size="large"
            placeholder="请选择计划开始时间"
            v-decorator="[
              'expect_start_at',
              {
                rules: [
                  {
                    type: 'object',
                    required: true,
                    message: '请选择计划开始时间!'
                  }
                ]
              }
            ]"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
        <a-form-item label="计划结束时间" :required="true">
          <a-date-picker
            size="large"
            placeholder="请选择计划结束时间"
            v-decorator="[
              'expect_finish_at',
              {
                rules: [
                  {
                    type: 'object',
                    required: true,
                    message: '请选择计划结束时间!'
                  }
                ]
              }
            ]"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
        <a-form-item label="预计工时" :required="true">
          <a-input
            placeholder="请输入预计工时"
            size="large"
            v-decorator="[
              'estimated_time',
              {
                rules: [{ required: true, message: '请输入预计工时!' }]
              }
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item label="附件">
          <a-upload-dragger
            v-decorator="[
              'files',
              {
                valuePropName: 'fileList',
                getValueFromEvent: normFile
              }
            ]"
            name="file"
            :multiple="false"
            action="/commons/qiniu_uploadFile"
            @change="handleChange"
            :beforeUpload="beforeUpload"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" style="color: #dddddd" />
            </p>
            <!-- <p class="ant-upload-text">点击或者拖拽文件来上传你的附件</p> -->
            <p class="ant-upload-hint" style="color: #ccc">
              点击或者拖拽文件来上传附件
            </p>
          </a-upload-dragger>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 12, offset: 10 }">
          <a-button type="primary" size="large" @click="handleSubmit">
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </page-layout>
</template>

<script>
import { add, detail, edit } from "@/services/task";
import { task } from "@/services/demand";
import { getDepartmentList } from "@/services/department";
import { getRequirementList,detail as requirement_detail} from "@/services/demand";
import { getUsers, getEngineers } from "@/services/user";
import PageLayout from "@/layouts/PageLayout";
import EditorBar from "@/components/wangEditor";
import moment from "moment";
export default {
  name: "demand",
  components: { PageLayout, EditorBar },
  data() {
    this.form = this.$form.createForm(this);
    return {
      isClear: false,
      detail: "",
      selectDatas: [],
      editData: {},
      principal_select: false,
      principal:'' ,
    };
  },
  created() {
    // 如果时编辑过来
    if (this.$route.query.id) {
      Promise.all([
        detail(this.$route.query.id),
        getDepartmentList(),
        getUsers({ type: 2 }),
        getRequirementList(),
        getEngineers()
      ]).then((arr) => {
        const editData = arr.splice(0, 1);
        this.editData = editData[0].data.data;
        // 设置值
        for (let key in this.form.getFieldsValue()) {
          if (key === "expect_start_at" || key === "expect_finish_at") {
            this.form.setFieldsValue({
              [key]: this.editData[key] ? moment(this.editData[key]) : ""
            });
            continue;
          }
          if (key === "files") {
            this.form.setFieldsValue({
              [key]:
                this.editData["file_content"] instanceof Array
                  ? this.editData["file_content"]
                  : []
            });
            continue;
          }
          this.form.setFieldsValue({ [key]: this.editData[key] });
        }

        this.selectDatas = arr.map((item) => {
          // if (item.data.code !== 20000) {
          //   this.$message.error("出错了，请刷新页面重试");
          // }
          return item.data.data;
        });
      });
    } else if (this.$route.query.demand_id) {
      // title docking_id engineer_id requirement_id
      // description expect_start_at expect_finish_at
      // estimated_time files
      Promise.all([
        task({
          requirement_id: this.$route.query.demand_id,
          change_id: this.$route.query.change_id
        }),
        getDepartmentList(),
        getUsers({ type: 2 }),
        getRequirementList(),
        getEngineers()
      ]).then((arr) => {
        const editData = arr.splice(0, 1);
        this.editData = editData[0].data.data;
        console.log(this.editData.principal_id);
        this.form.setFieldsValue({ title: this.editData["title"] });
        this.form.setFieldsValue({
          requirement_id: this.editData["requirement_id"]
        });
        this.form.setFieldsValue({ docking_id: this.editData["docking_id"] });
        this.form.setFieldsValue({
          principal_id: this.editData["principal_id"]
        });
        this.form.setFieldsValue({ description: this.editData["description"] });
        this.form.setFieldsValue({
          department_id: this.editData["department_id"]
        });
        this.selectDatas = arr.map((item) => {
          // if (item.data.code !== 20000) {
          //   this.$message.error("出错了，请刷新页面重试");
          // }
          return item.data.data;
        });
      });
    } else {
      Promise.all([
        getDepartmentList(),
        getUsers({ type: 2 }),
        getRequirementList(),
        getEngineers()
      ]).then((arr) => {
        // console.log(arr, "arr");
        this.selectDatas = arr.map((item) => {
          // if (item.data.code !== 20000) {
          //   this.$message.error("出错了，请刷新页面重试");
          // }
          return item.data.data;
        });
      });
    }
  },
  computed: {},
  methods: {
    handleRequirementChange(value) {
      this.principal_select = true;
      requirement_detail(value).then((res) => {
          if(res.data.code === 20000){
              this.principal = res.data.data.principal
          }
      })
    
    },
    moment,
    // 文本编辑器内容改变时的回调函数被
    change(val) {
      console.log(val, 111);
      console.log(this.detail, 111);
    },
    handleSelectChange() {
    
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        console.log(err, values);
        if (!err) {
          if (!this.$route.query.id) {
            add(values).then((res) => {
              // console.log(res, res);
              if (res.data.code === 20000) {
                this.$message.success({
                  content: res.data.message || "提交成功~",
                  onClose: () => {
                    this.form.resetFields();
                    this.$router.go(-1);
                  }
                });
              }
            });
          } else {
            edit({
              ...this.editData,
              ...values,
              id: this.$route.query.id
            }).then((res) => {
              // console.log(res, res);
              if (res.data.code === 20000) {
                this.$message.success({
                  content: res.data.message || "修改成功~",
                  onClose: () => {
                    this.form.resetFields();
                    this.$router.go(-1);
                  }
                });
              }
            });
          }
        }
      });
    },
    handleChange(info) {
      const status = info.file.status;
      if (status !== "uploading") {
        console.log(info.file, info.fileList);
      }
      if (status === "done") {
        // 服务端返回状态码不为 20000 时
        if (info.file.response.code !== 20000) {
          this.$message.error(info.file.response.message);
          this.form.setFieldsValue({ files: info.fileList.splice(-1, 1) });
          return false;
        }
        this.$message.success(`${info.file.name} 上传成功~`);
      } else if (status === "error") {
        this.$message.error(`${info.file.name} file upload failed.`);
      }
    },
    beforeUpload(file, fileList) {
      console.log(111);
      console.log(file, fileList);

      // console.log(this.form.getFieldValue("files"), 111);
      // if (fileList.length > 1) {
      //   this.$message.error("头像只能上传一张哦~");
      //   return false;
      // }
    },
    normFile(e) {
      console.log("Upload event:", e);
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    }
  }
};
</script>

<style lang="less" scoped>
</style>
